package org.common.convert.util;

import org.apache.commons.io.FileUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件工具类
 */
public class FileHelper {
    /**
     * 获取文件路径
     * @param fileFullName
     * @return
     */
    public static String getPath(String fileFullName) {
        String fileName = getFileName(fileFullName);
        String path = fileFullName.replaceAll(fileName,"");
        return path;
    }

    /**
     * 获取文件名
     * @param filePath
     * @return
     */
    public static String getFileName(String filePath) {
        int p = filePath.lastIndexOf("\\");
        if (p == -1) {
            p = filePath.lastIndexOf("/");
        }
        if (p == -1) {
            return filePath;
        }
        return filePath.substring(p + 1);
    }

    /**
     * 创建多层目录
     * @param dir
     * @return
     * @throws IOException
     */
    public static void createDir(String dir) throws IOException {
        //创建多层目录
        FileUtils.createParentDirectories(new java.io.File(dir));
    }
    public static void convertFileToUTF8(String fileName) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), StandardCharsets.ISO_8859_1));
        List<String> allLines = new ArrayList<>();

        reader.lines().forEach(line -> {
            allLines.add(line);
        });
        reader.close();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), StandardCharsets.UTF_8));

        for(String line : allLines){
            // 先用ISO-8859-1读取，因为GBK是双字节编码，直接读可能会乱码
            String decodedLine = new String(line.getBytes(StandardCharsets.ISO_8859_1), "GBK");
            // 再转换为UTF-8
            writer.write(decodedLine);
            writer.newLine();
        }
        writer.close();

    }

    public static long getFileLength(String fileName){
        File file = new File("path/to/your/file.txt");

        if (file.exists()) {
            return file.length();
        }else{
            return 0;
        }
    }
}
